package com.ndood.admin.core.exception;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import com.ndood.admin.pojo.comm.vo.AdminErrorVo;

import lombok.extern.slf4j.Slf4j;

/**
 * 自定义异常处理类
 */
@ControllerAdvice
@Slf4j
public class ControllerExceptionHandler {
	
	@Value("${debug}")
	private boolean debug;

	public static final String DEFAULT_ERROR_CODE = "10101";
	public static final String DEFAULT_MESSAGE = "系统错误";
	public static final String DEFAULT_ERROR_VIEW = "error/error";
	
	/**
	 * 对自定义异常进行处理
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(UserNotExistException.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	@ResponseBody
	public Map<String,Object> handlerUserNotException(UserNotExistException ex){
		Map<String, Object> result = new HashMap<>();
		result.put("id", ex.getId());
		result.put("message", ex.getMessage());
		return result;
	}

	/**
	 * 全局异常处理
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public Object errorHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {

		log.error("发生异常：" + e.getMessage(), e);
		if(debug) {
			e.printStackTrace();
		}

		if (isAjax(request) | isJson(request)) {
			AdminErrorVo error = new AdminErrorVo();
			if (e instanceof AdminException) {
				AdminException ae = (AdminException) e;
				error.setCode(ae.getCode() == null ? DEFAULT_ERROR_CODE : ae.getCode().getCode());
				error.setMsg(ae.getMessage() == null ? DEFAULT_MESSAGE : ae.getMessage());
				return error;
			}
			error.setCode(DEFAULT_ERROR_CODE);
			error.setMsg(e.getMessage() == null ? DEFAULT_MESSAGE : e.getMessage());
			return error;

		}

		ModelAndView mv = new ModelAndView();
		mv.addObject("exception", e);
		mv.addObject("url", request.getRequestURL());
		mv.setViewName(DEFAULT_ERROR_VIEW);
		return mv;

	}
	
	/**
	 * 判断是否是json请求
	 */
	public Boolean isJson(HttpServletRequest request) {
		boolean isJson = request.getHeader("content-type") != null
				&& request.getHeader("content-type").contains("json");
		return isJson;
	}

	/**
	 * 判断是否是ajax请求
	 */
	public static boolean isAjax(HttpServletRequest httpRequest) {
		boolean isAjax = httpRequest.getHeader("X-Requested-With") != null
				&& "XMLHttpRequest".equals(httpRequest.getHeader("X-Requested-With").toString());
		return isAjax;
	}
	
}